const multer = require('multer');
const fs = require('fs');
const path = require('path');

// 上传错误问题
const uploadErr = {
    'File too large': '文件大小超出限制',
    'reject fileType': '不允许上传的文件类型'
};

const uploadPath = './tempFiles';

// 文件上传配置
const upload = multer({
    // 文件限制大小
    limits: {
        fileSize: 1024 * 3000,
        files: 1
    },
    // 文件过滤
    fileFilter(req, file, cb) {
        if (file.mimetype == 'image/png' || file.mimetype == 'image/jpeg' || file.mimetype == 'image/gif') {
            cb(null, true)
        } else {
            cb('MulterError: reject fileType', false)
        }
    },
    storage: multer.diskStorage({
        // 上传的目标地址
        destination: (req, file, cb) => {
            // 如果目录不存在则创建
            if(!fs.existsSync(uploadPath)){
                fs.mkdtempSync(uploadPath);
            }
            console.log(uploadPath);
            cb(null, uploadPath);
        },
        // 定义上传的文件名
        filename: (req, file, cb) => {
            const ext = path.extname(file.originalname);
            const filename = `${Date.now()}_${Math.floor(Math.random() * 10000)}${ext}`;
            console.log(filename);
            cb(null, filename);
        }
    })
})

const uploadMiddleWare = upload.single('file');

exports.uploadMiddleWare = uploadMiddleWare;
exports.uploadErr = uploadErr;